package com.recipeexchange

import grails.test.*
import com.recipeexchange.domain.Recipe
import grails.plugins.nimble.core.UserBase
import org.apache.shiro.SecurityUtils
import com.recipeexchange.domain.User

class RecipeControllerTests extends ControllerUnitTestCase {

    def controller

    protected void setUp() {
        super.setUp()
        controller = new RecipeController()
    }

    protected void tearDown() {
        super.tearDown()
    }

    void testThatCreateOnlyCreatesNewRecipes() {
        mockDomain Recipe

        String description = 'description'
        mockParams.description = description
        controller.create()

        assertNotNull renderArgs.model.recipeInstance
        assertEquals description, renderArgs.model.recipeInstance.description
    }

    void testThatCreateActionCanEditRecipe(){
        Recipe expectedRecipe = new Recipe(id:123, recipe:'cook food')
        mockDomain Recipe, [expectedRecipe]

        mockParams.id = 123
        controller.create()

        assertEquals expectedRecipe, renderArgs.model.recipeInstance
    }

    void testThatLoggedInUserIsSetOnSavingARecipe(){
        def expectedUser = new User(id: 321)
        mockDomain UserBase, [expectedUser]
        setupCompleteMockedRecipeForBasicSaving()

        controller.save()

        assertEquals expectedUser, Recipe.findByUser(expectedUser).user
    }

    private void setupCompleteMockedRecipeForBasicSaving() {
        Recipe expectedRecipe = new Recipe(id: 123)
        mockDomain Recipe, [expectedRecipe]
        SecurityUtils.metaClass.static.getSubject = {[getPrincipal: {return 321}]}

        mockParams.recipe = 'cook food'
        mockParams.description = 'description'
        mockParams.name = 'name'
        mockParams.locator = 'll'
        mockParams.serves = '2-4'
        mockParams.ingredients = ''
        mockParams.recipeType = RecipeType.DESSERT
        mockParams.id = 123
    }
}
